from flask import Blueprint, jsonify, request, render_template
from app.models import User
from app import db, redis_client
import json
import time

main = Blueprint('main', __name__)

@main.route('/')
def index():
    return render_template('index.html')

@main.route('/user/<int:user_id>', methods=['GET'])
def get_user(user_id):
    start_time = time.time()
    
    # 首先尝试从Redis缓存获取用户数据
    cached_user = redis_client.get(f'user:{user_id}')
    
    if cached_user:
        query_time = (time.time() - start_time) * 1000  # 转换为毫秒
        return jsonify({
            'user': json.loads(cached_user),
            'source': 'redis',
            'query_time': round(query_time, 2)
        })
    
    # 如果缓存中没有，从MySQL数据库获取
    user = User.query.get_or_404(user_id)
    user_data = {
        'id': user.id,
        'username': user.username,
        'email': user.email,
        'created_at': user.created_at.isoformat()
    }
    
    # 将数据存入Redis缓存，设置过期时间为1小时
    redis_client.setex(
        f'user:{user_id}',
        3600,  # 1小时过期
        json.dumps(user_data)
    )
    
    query_time = (time.time() - start_time) * 1000  # 转换为毫秒
    return jsonify({
        'user': user_data,
        'source': 'mysql',
        'query_time': round(query_time, 2)
    })

@main.route('/user', methods=['POST'])
def create_user():
    data = request.get_json()
    
    user = User(
        username=data['username'],
        email=data['email']
    )
    
    db.session.add(user)
    db.session.commit()
    
    return jsonify({
        'message': 'User created successfully',
        'user_id': user.id
    }), 201 